package com.xinyue.server.framework.handler;

import com.xinyue.game.utils.encrypt.RsaKeyPair;
import com.xinyue.server.framework.common.GameServerUtil;
import com.xinyue.server.framework.handler.message.*;
import com.xinyue.server.framework.handlermapping.GameChannelContext;
import com.xinyue.server.framework.handlermapping.GameHandlerComponent;
import com.xinyue.server.framework.handlermapping.GameMapping;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Base64Utils;

import javax.annotation.PostConstruct;

/**
 * @author 王广帅
 * @since 2021/11/13 22:40
 */
@GameHandlerComponent
public class HandShakeHandler {
    private Logger logger = LoggerFactory.getLogger(HandShakeHandler.class);

    @PostConstruct()
    public void init() {
        logger.info("初始化握手处理类");
    }

    @GameMapping(GetPublicKeyRequest.class)
    public void getPublicKey(GameChannelContext ctx, GetPublicKeyRequest request) {
        try {
            RsaKeyPair rsaKeyPair = GameServerEncryptService.createAndBindRsaKeyPir(ctx.getNettyCtx().channel());
            byte[] rsaPublicKey = rsaKeyPair.getPublicKey();
            String publicKey = Base64Utils.encodeToString(rsaPublicKey);
            if (logger.isDebugEnabled()) {
                logger.debug("服务器公钥:{}", publicKey);
            }
            GetPublicKeyResponse response = new GetPublicKeyResponse();
            response.setPublicKey(publicKey);
            ctx.writeAndFlush(response);
        } catch (Exception e) {
            logger.error("获取公钥失败", e);
            ctx.writeAndFlush(e);
        }
    }

    @GameMapping(UploadAesKeyRequest.class)
    public void uploadAesKey(GameChannelContext ctx, UploadAesKeyRequest request) throws Exception {
        String aesKey = request.getAesKey();
        GameServerEncryptService.bindAesKey(ctx.getNettyCtx().channel(), aesKey);
        UploadAesKeyResponse response = new UploadAesKeyResponse();
        ctx.writeAndFlush(response);
    }

    @GameMapping(HeartbeatRequest.class)
    public void heartbeat(GameChannelContext gtx, HeartbeatRequest request) {
        logger.trace("收到心跳请求,channelId: {}", GameServerUtil.getChannelId(gtx.getNettyCtx().channel()));
        HeartbeatResponse response = new HeartbeatResponse();
        gtx.writeAndFlush(response);
    }
}
